package com.qys.training.server.controller;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.qys.training.base.dto.BaseResult;
import com.qys.training.biz.auth.service.HazelcastService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/hazelcast")
public class HazelcastController {
    public static final Logger logger = LoggerFactory.getLogger(HazelcastController.class);
    @Resource
    private HazelcastInstance hazelcastInstance;

    @Resource
    private HazelcastService hazelcastServiceImpl;

    @PostMapping(value = "/write")
    public BaseResult write(String key, String value) {
        IMap<Object, Object> customers = hazelcastInstance.getMap("customers");
        customers.put(key, value, 1, TimeUnit.DAYS);
        int write = hazelcastServiceImpl.write(key, value);
        return BaseResult.success("添加成功");
    }

    @GetMapping(value = "/read")
    public BaseResult read(String key) {
        IMap<Object, Object> map = hazelcastInstance.getMap("customers");
        Object obj = map.get(key);
        if (obj != null) {
            return BaseResult.success(obj.toString());
        } else {
            return BaseResult.success(hazelcastServiceImpl.select(key));
        }
    }

    @GetMapping(value = "/read-all")
    public Map<String, String> readAll() {
        return hazelcastInstance.getMap("customers");
    }

    @PostMapping(value = "/delete")
    public BaseResult delete(String key) {
        IMap<Object, Object> map = hazelcastInstance.getMap("customers");
        map.delete(key);
        hazelcastServiceImpl.delete(key);
        return BaseResult.success("删除成功");
    }

}
